package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;


public class RecordList extends ArrayList {
    private List<Record> recordList = new ArrayList<>();

    public RecordList(Record... records) {
        this.recordList = Arrays.asList(records);
    }

    public List<Record> getRecordList() {
        return recordList;
    }

    public List<?extends Record> getAvailableRecordList() {
        ArrayList<Record> result = new ArrayList<>();
        for (Record r : this.recordList) {
            if (r.isAvailable()) {
                result.add(r);
            }
        }
        return result;
    }

    public List<?extends Record> getAvailableBookList() {
        ArrayList<Record> result = new ArrayList<>();
        for (Record b : this.recordList) {
            if (b.isBook() && b.isAvailable()) {
                result.add(b);
            }
        }
        return result;
    }

    public List<?extends Record> getAvailableMovieList() {
        ArrayList<Record> result = new ArrayList<>();
        for (Record m : this.recordList) {
            if (m.isMovie() && m.isAvailable()) {
                result.add(m);
            }
        }
        return result;
    }

    public Record getRecordById(int id) {
        for (Record r : this.recordList) {
            if (r.getId() == id) {
                return r;
            }
        }
        throw new NoSuchElementException("No record with id " + id);
    }

    public void checkout(Record record) {
        if (storeManagesRecord(record)) {
            if (record.isAvailable()) {
                record.setStatus(RecordState.CHECKED_OUT);
            } else {
                throw new UnsupportedOperationException("Book already checked out!");
            }
        } else {
            throw new NoSuchElementException("No such book!");
        }
    }

    private boolean storeManagesRecord(Record record) {
        return this.recordList.contains(record);
    }

    public void giveBack(Record record) {
        if (!record.isAvailable()) {
            record.setStatus(RecordState.AVAILABLE);
        } else {
            throw new UnsupportedOperationException();
        }
    }
}
